package com.wolfking.jeesite.freemarker.method;

import com.wolfking.jeesite.freemarker.FreemarkerMethod;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;

@Slf4j
@FreemarkerMethod("toBase64")
public class ToBase64Method implements TemplateMethodModelEx {

    @Override
    public Object exec(List list) throws TemplateModelException {
        if (list.size() > 0) {
            if (list.get(0) == null) {
                return "";
            }
            try {
                return Base64.getEncoder().encode(list.get(0).toString().getBytes(StandardCharsets.UTF_8));
            } catch (Exception e) {
                return list.get(0).toString();
            }
        }
        return "";
    }
}